from os import remove
from base64 import b64encode
from io import BytesIO
from sqlite3 import connect
from PIL.Image import open
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QGridLayout, QApplication
from qdarkstyle import load_stylesheet_pyqt5
from matplotlib.pyplot import rcParams, figure, subplots, MultipleLocator
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from U_Redraw_calcu_code import Redraw_AoP

rcParams['font.size'] = 10
rcParams['font.family'] = 'Times New Roman'
rcParams['axes.unicode_minus'] = False

class Loc_Sim_Matplot_Dialog(QWidget):

    def __init__(self, img_path1, img_path2, img_path3, FLIP_PHOTO, save_manager):
        super(Loc_Sim_Matplot_Dialog, self).__init__()
        self.ax1 = None
        self.setWindowTitle("AOE and DOP")
        self.resize(1100, 416)
        self.setWindowModality(Qt.WindowModal)
        self.setStyleSheet('background-color: #ffffff;')
        self.img_path1 = img_path1
        self.img_path2 = img_path2
        self.img_path3 = img_path3
        self.flip_image = FLIP_PHOTO
        self.save_manager = save_manager

        self.VBoxLayout = QVBoxLayout()
        self.fig1 = figure()
        self.canvas1 = FigureCanvas(self.fig1)

        self.fig3, self.ax3 = subplots()
        self.canvas3 = FigureCanvas(self.fig3)
        self.canvas3.setMinimumHeight(50)
        self.canvas3.setMaximumHeight(100)

        self.fig6 = figure()
        self.ax6 = None
        self.canvas6 = FigureCanvas(self.fig6)

        self.Right_LayoutZ = QVBoxLayout()
        self.Right_Layout = QGridLayout()

        self.Right_Layout.addWidget(self.canvas1, 0, 0)
        self.Right_Layout.addWidget(self.canvas3, 1, 0, 1, 2)
        self.Right_Layout.addWidget(self.canvas6, 0, 1)

        self.Right_LayoutZ.addLayout(self.Right_Layout)
        self.VBoxLayout.addLayout(self.Right_LayoutZ)
        self.setLayout(self.VBoxLayout)

        self.setup_signal()

    def setup_signal(self):
        print(f'action to Polarized')
        reAoP = Redraw_AoP(self.img_path1, self.img_path2, self.img_path3, self.flip_image)
        aoe, aop, dop = reAoP.Redraw_AoP1()

        self.ax1 = self.fig1.subplots()
        self.ax1.imshow(aoe, cmap='jet')
        self.ax1.set_axis_off()
        self.ax1.yaxis.set_major_locator(MultipleLocator(200))
        self.ax1.axis("equal")
        self.canvas1.draw()

        self.ax6 = self.fig6.subplots()
        self.ax6.imshow(dop, cmap='jet')
        self.ax6.set_axis_off()
        self.ax6.yaxis.set_major_locator(MultipleLocator(200))
        self.ax6.axis("equal")
        self.canvas6.draw()

        self.fig3.subplots_adjust(bottom=0.6)
        norm = Normalize(vmin=-80, vmax=80)
        self.fig3.colorbar(
            ScalarMappable(norm=norm, cmap="jet"),
            cax=self.ax3,
            ticks=[-80, -60, -40, -20, 0, 20, 40, 60, 80],
            orientation='horizontal')
        self.canvas3.draw()
        NAME_FORWARD = self.img_path2[-26: -7]
        SAVE_MANAGE = ['不保存', '本机', '数据库', '本机和数据库']

        SAVE_AOP = "./REASULT_POLARIZATION_DISTRIBUTION_IMAGE/" + NAME_FORWARD + "-AOP.jpg"
        SAVE_DOP = "./REASULT_POLARIZATION_DISTRIBUTION_IMAGE/" + NAME_FORWARD + "-DOP.jpg"
        SAVE_AOE = "./REASULT_POLARIZATION_DISTRIBUTION_IMAGE/" + NAME_FORWARD + "-AOE.jpg"
        SAVE_AOE_CONTOURF = "./REASULT_POLARIZATION_DISTRIBUTION_IMAGE/" + NAME_FORWARD + "-AOE_CONTOURF.jpg"

        if self.save_manager == SAVE_MANAGE[0]:
            print("不保存")
        elif self.save_manager == SAVE_MANAGE[1]:
            self.fig6.savefig(SAVE_DOP)
            self.fig1.savefig(SAVE_AOE)
        elif self.save_manager == SAVE_MANAGE[2]:
            con = connect("db/Image_database.db")
            cur = con.cursor()
            symbol = 'REASULT_IMAGE'
            try:
                cur.execute("create table IF NOT EXISTS %s(PIC_NAME TEXT, IMAGE_BYTES BLOB)" % symbol)
                con.commit()
                pass
            except Exception as e:
                print(e, "create table failed")

            self.fig6.savefig(SAVE_DOP)
            self.fig1.savefig(SAVE_AOE)

            SQL = f"INSERT OR REPLACE INTO REASULT_IMAGE (PIC_NAME, IMAGE_BYTES) VALUES (?, ?);"
            AOP_IMAGE = open(SAVE_AOP)
            AOP_BUFFER = BytesIO()
            AOP_IMAGE.save(AOP_BUFFER, format='JPEG')
            AOP_DATA = AOP_BUFFER.getvalue()

            BASE64_AOP = b64encode(AOP_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-AOP.jpg", BASE64_AOP))
            con.commit()
            remove(SAVE_AOP)

            DOP_IMAGE = open(SAVE_DOP)
            DOP_BUFFER = BytesIO()
            DOP_IMAGE.save(DOP_BUFFER, format='JPEG')
            DOP_DATA = DOP_BUFFER.getvalue()

            BASE64_DOP = b64encode(DOP_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-DOP.jpg", BASE64_DOP))
            con.commit()
            remove(SAVE_DOP)

            AOE_IMAGE = open(SAVE_AOE)
            AOE_BUFFER = BytesIO()
            AOE_IMAGE.save(AOE_BUFFER, format='JPEG')
            AOE_DATA = AOE_BUFFER.getvalue()

            BASE64_AOE = b64encode(AOE_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-_AOE.jpg", BASE64_AOE))
            con.commit()
            remove(SAVE_AOE)

            AOE_CONTOURF_IMAGE = open(SAVE_AOE_CONTOURF)
            SAVE_AOE_CONTOURF_BUFFER = BytesIO()
            AOE_CONTOURF_IMAGE.save(SAVE_AOE_CONTOURF_BUFFER, format='JPEG')
            SAVE_AOE_CONTOURF_DATA = SAVE_AOE_CONTOURF_BUFFER.getvalue()

            BASE64_AOE_CONTOURF = b64encode(SAVE_AOE_CONTOURF_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-AOE_CONTOURF.jpg", BASE64_AOE_CONTOURF))
            con.commit()
            remove(SAVE_AOE_CONTOURF)
            con.close()

        elif self.save_manager == SAVE_MANAGE[3]:
            con = connect("db/Image_database.db")
            cur = con.cursor()
            symbol = 'REASULT_IMAGE'
            try:
                cur.execute("create table IF NOT EXISTS %s(PIC_NAME TEXT, IMAGE_BYTES BLOB)" % symbol)
                con.commit()
                pass
            except Exception as e:
                print(e, "create table failed")

            self.fig6.savefig(SAVE_DOP)
            self.fig1.savefig(SAVE_AOE)

            SQL = f"INSERT OR IGNORE INTO REASULT_IMAGE (PIC_NAME, IMAGE_BYTES) VALUES (?, ?);"

            AOP_IMAGE = open(SAVE_AOP)
            AOP_BUFFER = BytesIO()
            AOP_IMAGE.save(AOP_BUFFER, format='JPEG')
            AOP_DATA = AOP_BUFFER.getvalue()

            BASE64_AOP = b64encode(AOP_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-AOP.jpg", BASE64_AOP))
            con.commit()

            DOP_IMAGE = open(SAVE_DOP)
            DOP_BUFFER = BytesIO()
            DOP_IMAGE.save(DOP_BUFFER, format='JPEG')
            DOP_DATA = DOP_BUFFER.getvalue()

            BASE64_DOP = b64encode(DOP_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-DOP.jpg", BASE64_DOP))
            con.commit()

            AOE_IMAGE = open(SAVE_AOE)
            AOE_BUFFER = BytesIO()
            AOE_IMAGE.save(AOE_BUFFER, format='JPEG')
            AOE_DATA = AOE_BUFFER.getvalue()

            BASE64_AOE = b64encode(AOE_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-_AOE.jpg", BASE64_AOE))
            con.commit()


            AOE_CONTOURF_IMAGE = open(SAVE_AOE_CONTOURF)
            SAVE_AOE_CONTOURF_BUFFER = BytesIO()
            AOE_CONTOURF_IMAGE.save(SAVE_AOE_CONTOURF_BUFFER, format='JPEG')
            SAVE_AOE_CONTOURF_DATA = SAVE_AOE_CONTOURF_BUFFER.getvalue()

            BASE64_AOE_CONTOURF = b64encode(SAVE_AOE_CONTOURF_DATA)
            cur.execute(SQL, (NAME_FORWARD + "-AOE_CONTOURF.jpg", BASE64_AOE_CONTOURF))
            con.commit()
            con.close()

        print(f'success to Polarized')


if __name__ == '__main__':
    from sys import argv, exit
    app = QApplication(argv)
    app.setStyleSheet(load_stylesheet_pyqt5())
    path1 = r'E:\CanonImage\11.25\3图像坐标系xS_yE\2022-11-25 16-35-40 0°.JPG'
    path2 = r'E:\CanonImage\11.25\3图像坐标系xS_yE\2022-11-25 16-35-40 60°.JPG'
    path3 = r'E:\CanonImage\11.25\3图像坐标系xS_yE\2022-11-25 16-35-40 120°.JPG'
    SAVE_MANAGE = ['不保存', '本机', '数据库', '本机和数据库']
    MainWindow = Loc_Sim_Matplot_Dialog(path3, path1, path2, False, SAVE_MANAGE[0])
    MainWindow.show()
    exit(app.exec_())
